package com.restlet.spike.filter;

import org.restlet.Filter;
import org.restlet.util.Series;
import org.restlet.data.Request;
import org.restlet.data.Response;
import org.restlet.data.Method;
import com.noelios.restlet.http.HttpConstants;

public class ExtraHttpMethodOverrideFilter extends Filter {

    protected int beforeHandle(Request request, Response response) {
        handleHttpMethodOverride(request);

        return CONTINUE;
    }

    @SuppressWarnings("unchecked")
    private final void handleHttpMethodOverride(Request request) {
        final Series extraHeaders = (Series) request.getAttributes().get(
                HttpConstants.ATTRIBUTE_HEADERS);
        final String overrideValue = extraHeaders.getFirstValue(
                HttpConstants.HEADER_X_HTTP_METHOD_OVERRIDE, true);

        if (overrideValue != null && overrideValue.trim().length() > 0) {
            if (request.getMethod().equals(Method.POST)
                    && overrideValue.trim().equalsIgnoreCase(Method.PUT.getName())) {
                request.setMethod(Method.PUT);
            } else if (request.getMethod().equals(Method.POST)
                    && overrideValue.trim().equalsIgnoreCase(Method.DELETE.getName())) {
                request.setMethod(Method.DELETE);
            }
        }
    }
}
